//
// Created by jiazhong on 2023/11/9.
//

#include "JavaCallHelper.h"
#include "log.h"

JavaCallHelper::JavaCallHelper(JavaVM *_javaVM, JNIEnv *_env, jobject &_jobj) : javaVM(_javaVM), env(_env) {
    // 局部变量变成 全局变量  jni
    jobj = env->NewGlobalRef(_jobj);
    jclass jclazz = env->GetObjectClass(jobj);
    jMethodId_postData = env->GetMethodID(jclazz, "postData", "([B)V");
}

void JavaCallHelper::postH264(char *data, int length, int thread) {
    // byte[]
    jbyteArray array = env->NewByteArray(length);
    env->SetByteArrayRegion(array, 0, length, reinterpret_cast<const jbyte *>(data));
    if (thread == THREAD_CHILD) {
        JNIEnv *jniEnv;
        if (javaVM->AttachCurrentThread(&jniEnv, nullptr) != JNI_OK) {
            return;
        }
        jniEnv->CallVoidMethod(jobj, jMethodId_postData, array);
        javaVM->DetachCurrentThread();
    } else {
        env->CallVoidMethod(jobj, jMethodId_postData, array);
    }
}

JavaCallHelper::~JavaCallHelper() {
    LOGE("JavaCallHelper Destroy");
    env->DeleteGlobalRef(jobj);
    jobj = nullptr;
}

